#include "searchdialog.h"
#include "ui_searchdialog.h"
#include <QCompleter>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include <QTextStream>
#include <QFile>
#include "searchatom.h"

namespace DataBaseStructure
{
    namespace GamesTable
    {
        enum{ID=0, white_player, black_player, moves, result, site, event, date};
    }

    namespace PlayersTable
    {
        enum{ID=0, name, pgotoURL};
    }
}

SearchDialog::SearchDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SearchDialog)
{
    ui->setupUi(this);
    ui->feelLuckyBttn->hide();
    if(dBHandler.isOpen())
    {
        ui->connectionStatusLabel->setText("Alive");
        ui->connectionStatusLabel->setStyleSheet("color: green;");
    }
    else
    {
        ui->connectionStatusLabel->setText("Dead");
        ui->connectionStatusLabel->setStyleSheet("color: red;");
    }
    qDebug("inserting");

    qDebug("Inserted");
}


QString SearchDialog::getPlayersIdByName(QString name)
{
    QSqlQuery query = dBHandler.exec(QString("SELECT `ID` FROM `players` WHERE `name`= '%1'").arg(name));
           // qDebug()<<query.lastQuery().toStdString().c_str();
    if(query.isSelect() && query.isActive() && query.size() >0)
    {
        query.first();
        return query.value(0).toString();
        }
    else return "-1";
    query.finish();
}

QString SearchDialog::getPlayersNameByID(QString id)
{
    QSqlQuery query = dBHandler.exec(QString("SELECT `name` FROM `players` WHERE `ID`= '%1'").arg(id));
            // qDebug()<<query.lastQuery().toStdString().c_str();
    if(query.isSelect() && query.isActive() && query.size() >0)
    {
        query.first();
        return query.value(0).toString();
        }
    else return "-1";
    query.finish();
}


QString SearchDialog::convertResult(int result)
{
    if(result == 1)
        return "1-0";
    if(result == 2)
        return "0-1";
    return "1/2-1/2";
}

QString SearchDialog::resultFilename()
{
    return resFile;
}

SearchDialog::~SearchDialog()
{
    delete ui;
}

void SearchDialog::on_findBttn_clicked()
{
    ui->resultListWidget->clear();
    QString queryText("SELECT * FROM `games` WHERE ");
    QString fPlayersText = "TRUE";
    QString sPlayersText = "TRUE";

    if(!ui->firstPlayerNameCombo->currentText().isEmpty())
    {
        fPlayersText = getPlayersIdByName(ui->firstPlayerNameCombo->currentText());
        sPlayersText = fPlayersText;
    }
    if(ui->secondPlayerCheck->isChecked() && (!ui->secondPlayersCombo->currentText().isEmpty()))
        sPlayersText = getPlayersIdByName(ui->secondPlayersCombo->currentText());

    if(ui->secondPlayerCheck->isChecked())
    {
        if(ui->whiteRadio->isChecked())
        {
            queryText.append(" `white_player` = ")
                    .append(fPlayersText)
                    .append(" AND ")
                    .append(" `black_player` = ")
                    .append(sPlayersText);
        }
        else if(ui->blackRadio->isChecked())
        {
            queryText.append(" `black_player` = ")
                    .append(fPlayersText)
                    .append(" AND ")
                    .append(" `white_player` = ")
                    .append(sPlayersText);
        }
    }
    else
        if(ui->whiteRadio->isChecked())
        {
            queryText.append(" `white_player` = ")
                    .append(fPlayersText);
        }
        else if(ui->blackRadio->isChecked())
        {
            queryText.append(" `black_player` = ")
                    .append(fPlayersText);
        }
        else
        {
            queryText.append(" `black_player` = ")
                    .append(fPlayersText)
                    .append(" OR ")
                    .append(" `white_player` = ")
                    .append(fPlayersText);
        }

    if(ui->secondPlayerCheck->isChecked() && ui->nMRadio->isChecked())
    {
        QString fPart = "SELECT * FROM `games` WHERE ";
        fPart.append(" `black_player` = ")
                .append(fPlayersText)
                .append(" AND ")
                .append(" `white_player` = ")
                .append(sPlayersText);

        QString sPart = "SELECT * FROM `games` WHERE ";
        sPart.append(" `black_player` = ")
                .append(sPlayersText)
                .append(" AND ")
                .append(" `white_player` = ")
                .append(fPlayersText);

        queryText = QString("SELECT * FROM (%1 UNION %2) crossSelect WHERE TRUE").arg(fPart, sPart);
    }

    if(ui->resultDefinition->isChecked())
    {
        if(ui->resultCombo->currentIndex() == 1)
            queryText.append(" AND `result` = 1");
        else if(ui->resultCombo->currentIndex() == 2)
            queryText.append(" AND `result` = 2");
        else if(ui->resultCombo->currentIndex() == 3)
            queryText.append(" AND `result` = 3");
    }


    //queryText.append(fPlayersText).append(delimeter).append(sPlayersText);

    // qDebug()<<queryText;
    QSqlQuery query = dBHandler.exec(queryText);
    ui->resultListWidget->clear();
    ui->resultListWidget->setEnabled(true);
    if(query.isSelect() && query.isActive())
    {
        resFile = QString("%1.pgn").arg(rand());
        QFile data(resFile);
        if(data.open(QFile::WriteOnly))
        {
            QTextStream out(&data);
            while(query.next())
            {
                QListWidgetItem *tmp = new QListWidgetItem(0);
                ui->resultListWidget->addItem(tmp);
                SearchAtom *tmpA = new SearchAtom(0);
                tmpA->setWhitePlayer(getPlayersNameByID(
                        query.value(DataBaseStructure::GamesTable::white_player)
                        .toString()
                        ));

                tmpA->setResult(convertResult(query.value(DataBaseStructure::GamesTable::result).toInt()));

                tmpA->setBlackPlayer(getPlayersNameByID(
                        query.value(DataBaseStructure::GamesTable::black_player)
                        .toString()
                        ));

                tmp->setSizeHint(tmpA->minimumSizeHint());

                ui->resultListWidget->setItemWidget(tmp, tmpA);
                out<<"[Event \""<<query.value(DataBaseStructure::GamesTable::event).toString()<<"\"]\n";
                out<<"[Site \""<<query.value(DataBaseStructure::GamesTable::site).toString()<<"\"]\n";
                out<<"[Date \""<<query.value(DataBaseStructure::GamesTable::date).toString()<<"\"]\n";
                out<<"[Round \"??\"]\n";
                out<<"[White \""<<
                        getPlayersNameByID(query.value(DataBaseStructure::GamesTable::white_player).toString())<<"\"]\n";
                out<<"[Black \""<<
                        getPlayersNameByID(query.value(DataBaseStructure::GamesTable::black_player).toString())<<"\"]\n";
                out<<"[Result \""<<convertResult(query.value(DataBaseStructure::GamesTable::result).toInt())<<"\"]\n\n";
                out<<query.value(DataBaseStructure::GamesTable::moves).toString()
                        <<" "<<convertResult(query.value(DataBaseStructure::GamesTable::result).toInt())<<"\n\n\n";
            }
            data.close();
            query.finish();
        }
    }
    else
        // qDebug()<<dBHandler.lastError().text();
    ui->matchesCountLabel->setText(
            QString("Matches: %1")
            .arg(ui->resultListWidget->count()));
}

void SearchDialog::on_firstPlayerNameCombo_editTextChanged(QString curr)
{
    if(curr.isEmpty() &&
       ui->secondPlayersCombo->currentText().isEmpty() &&
       ui->nMRadio->isChecked() && ui->resultCombo->currentIndex() ==0)
        ui->findBttn->setEnabled(false);
    else
        ui->findBttn->setEnabled(true);
    if(curr.length()>3)
    {
        QStringList results;
        QSqlQuery query = dBHandler.exec(QString("SELECT `name` FROM `players` WHERE `name` LIKE '%1\%'").arg(curr));
        if(query.isSelect() && query.isActive())
        {
            while(query.next())
            {
                results<<query.value(0).toString();
            }
            query.finish();
        }
        else;
            // qDebug()<<dBHandler.lastError().text();
        // qDebug()<<results;
        QCompleter *c= new QCompleter(results);
        ui->firstPlayerNameCombo->setCompleter(c);
    }
}

void SearchDialog::on_secondPlayerCheck_stateChanged(int )
{
    ui->secondPlayersCombo->setEnabled(ui->secondPlayerCheck->isChecked());
}

void SearchDialog::on_secondPlayersCombo_editTextChanged(QString curr)
{
    if(curr.isEmpty() &&
       ui->secondPlayersCombo->currentText().isEmpty() &&
       ui->nMRadio->isChecked() && ui->resultCombo->currentIndex() ==0)
        ui->findBttn->setEnabled(false);
    else
        ui->findBttn->setEnabled(true);
    if(curr.length()>3)
    {
        QStringList results;
        QSqlQuery query = dBHandler.exec(QString("SELECT `name` FROM `players` WHERE `name` LIKE '%1\%'").arg(curr));
        if(query.isSelect() && query.isActive())
        {
            while(query.next())
            {
                results<<query.value(0).toString();
            }
            query.finish();
        }
        else;
            // qDebug()<<dBHandler.lastError().text();
        // qDebug()<<results;
        QCompleter *c= new QCompleter(results);
        ui->secondPlayersCombo->setCompleter(c);
    }
}

void SearchDialog::on_resultDefinition_stateChanged(int )
{
    ui->resultCombo->setEnabled(ui->resultDefinition->isEnabled());
}

void SearchDialog::on_exitBttn_clicked()
{
    close();
}
